package com.dmai.capacity.platform.user.pojo;

import lombok.Data;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fengtangquan on 2019/7/23.
 */
@Data
public class TreeExtVo<T> {
    private static final long serialVersionUID = 749360940290141180L;

    private String id;

    private String parentId;

    private T data;

    private List<TreeExtVo<T>> childNodes;

    /**
     * 两层递归实现建树
     */
    public List<TreeExtVo<T>> toTree(List<TreeExtVo<T>> treeList) {

        Map<String, List<TreeExtVo<T>>> childrenMap = new HashMap<>();
        Map<String, TreeExtVo> parentMap = new HashMap<>();
        List<TreeExtVo<T>> res = new ArrayList<>();

        for (TreeExtVo node : treeList) {
            if (!childrenMap.containsKey(node.getParentId())) {
                childrenMap.put(node.getParentId(), new ArrayList<>());
            }
            if (!CollectionUtils.isEmpty(childrenMap.get(node.getParentId()))) {
                childrenMap.get(node.getParentId()).add(node);
            }
            parentMap.put(node.getParentId(), node);

            if (!childrenMap.containsKey(node.getId())) {
                List<TreeExtVo<T>> childList = new ArrayList<>();
                childList.add(node);
                childrenMap.put(node.getId(), childList);
            }
            node.setChildNodes(childrenMap.get(node.getId()));

            for (Map.Entry<String, List<TreeExtVo<T>>> entry : childrenMap.entrySet()) {
                if (!parentMap.containsKey(entry.getKey())) {
                    res.addAll(entry.getValue());
                }
            }
        }
        return res;
    }
}
